#include "Widget.h"
#include "ui_Widget.h"
#include <QHostAddress>
#include<QCloseEvent>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(onLogin()));
    connect(ui->lineEditSent,SIGNAL(returnPressed()),this,SLOT(onSent()));
    client=0;
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onLogin()
{
    QString name= ui->lineEditUserName->text().trimmed();
    if(name.isEmpty())
    {
        setWindowTitle("UserName is empty!");
        return;
    }
    QString host=ui->lineEditHost->text().trimmed();
    if(host.isEmpty())
    {
        setWindowTitle("Host is empty!");
        return;
    }
    QString port=ui->lineEditPort->text().trimmed();
    if(port.isEmpty())
    {
        setWindowTitle("port is empty");
        return;
    }
    if(!client)
    {
        client=new QTcpSocket(this);
        connect(client,SIGNAL(readyRead()),this,SLOT(onShow()));
        connect(client,SIGNAL(connected()),this,SLOT(onLogined()));
        client->connectToHost(QHostAddress(host),port.toInt());
    }
    ui->stackedWidget->setCurrentIndex(1);

}

void Widget::onSent()
{
    QByteArray sent=ui->lineEditSent->text().trimmed().toUtf8();
    client->write("say "+sent);
}

void Widget::onShow()
{
//    ui->textEditShow->append(client->readAll().replace("\n",""));
}

void Widget::onLogined()
{
    client->write(ui->lineEditUserName->text().toUtf8());
}

void Widget::closeEvent(QCloseEvent *event)
{
    event->ignore();
    this->hide();
}
